<template>
  <div class="realtime-contest-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="15" animated />
    </div>

    <!-- 竞赛内容 -->
    <div v-else class="contest-main">
      <!-- 竞赛头部信息 -->
      <div class="contest-header">
        <div class="contest-title">
          <h2>{{ contestInfo?.title || '实时竞赛' }}</h2>
          <el-tag v-if="contestInfo" type="success">正在进行</el-tag>
        </div>
        <div class="contest-info">
          <div class="contest-timer">
            <el-icon><Timer /></el-icon>
            <span :class="{'timer-warning': remainingTime <= 10}">{{ formatTime(remainingTime) }}</span>
          </div>
          <div class="question-progress">
            <span>进度: {{ currentQuestionIndex + 1 }} / {{ totalQuestions }}</span>
            <el-progress :percentage="progressPercentage"></el-progress>
          </div>
        </div>
      </div>

      <div class="contest-body">
        <!-- 左侧答题区域 -->
        <div class="left-panel">
          <!-- 题目内容 -->
          <div class="question-area">
            <div v-if="!currentQuestion" class="no-question">
              <el-empty description="等待题目加载...">
                <template #extra>
                  <el-button type="primary" @click="requestCurrentQuestion" round>
                    刷新题目
                  </el-button>
                </template>
              </el-empty>
            </div>
            
            <template v-else>
              <div class="question-header">
                <div class="question-position">
                  <div class="question-number">第 {{ currentQuestionIndex + 1 }} 题 <span class="question-total">/ {{ totalQuestions }}</span></div>
                </div>
                <div class="question-info">
                  <el-tag effect="plain" round class="question-type">
                    {{ currentQuestion.typeName || getQuestionTypeText(currentQuestion.typeId) }}
                  </el-tag>
                  <el-tag effect="plain" round class="question-difficulty" :type="getDifficultyType(currentQuestion.difficulty)">
                    {{ getDifficultyText(currentQuestion.difficulty) }}
                  </el-tag>
                  <span class="question-score">{{ currentQuestion.score || 0 }}分</span>
                </div>
              </div>
              
              <div class="question-content">
                <h3>{{ currentQuestion.content }}</h3>
              </div>
              
              <!-- 选择题选项 -->
              <div v-if="[1, 2].includes(currentQuestion.typeId)" class="question-options">
                <el-radio-group v-if="currentQuestion.typeId === 1" v-model="userAnswer" class="option-group">
                  <el-radio
                    v-for="option in currentQuestion.options"
                    :key="option.id"
                    :label="option.optionOrder"
                    class="option-item"
                    border
                  >
                    <div class="option-wrapper">
                      <span class="option-key">{{ option.optionOrder }}.</span>
                      <span class="option-content">{{ option.optionContent }}</span>
                    </div>
                  </el-radio>
                </el-radio-group>
                
                <el-checkbox-group v-else v-model="userMultipleAnswer" class="option-group">
                  <el-checkbox
                    v-for="option in currentQuestion.options"
                    :key="option.id"
                    :label="option.optionOrder"
                    border
                    class="option-item"
                  >
                    <div class="option-wrapper">
                      <span class="option-key">{{ option.optionOrder }}.</span>
                      <span class="option-content">{{ option.optionContent }}</span>
                    </div>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              
              <!-- 判断题 -->
              <div v-else-if="currentQuestion.typeId === 3" class="question-options">
                <el-radio-group v-model="userAnswer" class="option-group truth-false">
                  <el-radio label="T" border class="option-item tf-option">
                    <div class="option-wrapper">
                      <span class="option-key">T.</span>
                      <span class="option-content">正确</span>
                    </div>
                  </el-radio>
                  <el-radio label="F" border class="option-item tf-option">
                    <div class="option-wrapper">
                      <span class="option-key">F.</span>
                      <span class="option-content">错误</span>
                    </div>
                  </el-radio>
                </el-radio-group>
              </div>
              
              <!-- 填空题 -->
              <div v-else-if="currentQuestion.typeId === 4" class="question-options">
                <el-input
                  v-model="userAnswer"
                  type="text"
                  placeholder="请输入答案"
                  class="blank-answer"
                />
              </div>
              
              <!-- 简答题 -->
              <div v-else-if="currentQuestion.typeId === 5" class="question-options">
                <el-input
                  v-model="userAnswer"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入答案"
                  resize="none"
                  class="essay-answer"
                  maxlength="1000"
                  show-word-limit
                />
              </div>
              
              <div class="question-actions">
                <el-button 
                  type="primary" 
                  round 
                  :disabled="!canSubmitAnswer" 
                  @click="submitAnswer"
                  size="large"
                  class="submit-btn"
                >
                  提交答案
                </el-button>
              </div>
            </template>
          </div>
        </div>
        
        <!-- 右侧排名区域 -->
        <div class="right-panel">
          <div class="ranking-area">
            <h3 class="ranking-title">实时排名</h3>
            <div class="ranking-list">
              <el-empty v-if="rankings.length === 0" description="暂无排名数据" />
              <el-scrollbar v-else height="600px">
                <div
                  v-for="(rank, index) in rankings"
                  :key="rank.userId"
                  class="ranking-item"
                  :class="{'current-user': rank.userId === currentUserId, 'top-three': index < 3}"
                >
                  <div class="rank-position">
                    <el-tag
                      v-if="index < 3"
                      :type="getTopThreeType(index)"
                      effect="dark"
                      class="rank-tag"
                    >
                      {{ index + 1 }}
                    </el-tag>
                    <span v-else class="rank-number">{{ index + 1 }}</span>
                  </div>
                  <div class="rank-user">
                    <el-avatar :size="36" :src="rank.userAvatar">
                      {{ rank.nickname?.substring(0, 1) || 'U' }}
                    </el-avatar>
                    <span class="rank-username">{{ rank.nickname || '未知用户' }}</span>
                  </div>
                  <div class="rank-score">{{ rank.score || 0 }}分</div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 答题结果弹窗 -->
    <el-dialog
      v-model="showAnswerResult"
      :title="answerCorrect ? '回答正确！' : '回答错误'"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="answer-result">
        <el-result
          :icon="answerCorrect ? 'success' : 'error'"
          :title="answerCorrect ? '恭喜！' : '加油！'"
          :sub-title="answerResultMessage"
        >
        </el-result>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeResultDialog" round>
            {{ answerCorrect ? '太棒了' : '明白了' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 竞赛结束弹窗 -->
    <el-dialog
      v-model="showContestEnd"
      title="竞赛已结束"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="contest-end">
        <el-result
          icon="success"
          title="竞赛已结束"
          sub-title="感谢您的参与！"
        >
          <template #extra>
            <div class="end-actions">
              <el-button type="primary" @click="goToRanking" round>查看排名</el-button>
              <el-button @click="goToContestList" round>返回竞赛列表</el-button>
            </div>
          </template>
        </el-result>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getContestDetail } from '@/api/contest'
import { getUserInfo } from '@/api/user'
import { getQuestionsByContestId } from '@/api/question'

export default {
  name: 'RealTimeContest',
  
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 基础数据
    const contestId = ref(parseInt(route.params.id) || 0)
    const contestInfo = ref({})
    const currentQuestion = ref(null)
    const currentQuestionIndex = ref(0)
    const totalQuestions = ref(0)
    const loading = ref(true)
    const rankings = ref([])
    const currentUserId = ref(null)
    
    // 答题相关
    const userAnswer = ref('')
    const userMultipleAnswer = ref([])
    const timeLimit = ref(0)
    const remainingTime = ref(0)
    const timer = ref(null)
    const hasSubmittedAnswer = ref(false)  // 是否已提交答案
    const lastQuestionId = ref(null)  // 上一题ID，用于检测题目切换
    
    // 结果展示
    const showAnswerResult = ref(false)
    const answerCorrect = ref(false)
    const answerResultMessage = ref('')
    const showContestEnd = ref(false)
    
    // WebSocket连接
    const webSocket = ref(null)
    
    // 新增题目列表存储
    const questionsList = ref([])
    
    // 已回答的题目ID列表
    const answeredQuestions = ref([])
    
    // 计算进度百分比
    const progressPercentage = computed(() => {
      if (totalQuestions.value <= 0) return 0;
      return Math.floor(((currentQuestionIndex.value + 1) / totalQuestions.value) * 100);
    })
    
    // 计算是否可提交答案
    const canSubmitAnswer = computed(() => {
      // 如果已经提交过答案，则不能再次提交
      if (hasSubmittedAnswer.value) {
        return false;
      }
      
      if (!currentQuestion.value) return false;
      
      // 单选题或判断题
      if ([1, 3].includes(currentQuestion.value.typeId)) {
        return userAnswer.value !== '';
      }
      // 多选题
      else if (currentQuestion.value.typeId === 2) {
        return userMultipleAnswer.value.length > 0;
      }
      // 填空题或简答题
      else {
        return userAnswer.value.trim() !== '';
      }
    })
    
    // 获取题目类型文本
    const getQuestionTypeText = (typeId) => {
      const types = {
        1: '单选题',
        2: '多选题',
        3: '判断题',
        4: '填空题',
        5: '简答题'
      }
      return types[typeId] || '未知类型'
    }
    
    // 获取难度文本
    const getDifficultyText = (difficulty) => {
      const levels = {
        1: '简单',
        2: '中等',
        3: '困难'
      }
      return levels[difficulty] || '未知难度'
    }
    
    // 获取难度类型（用于标签颜色）
    const getDifficultyType = (difficulty) => {
      const types = {
        1: 'success',
        2: 'warning',
        3: 'danger'
      }
      return types[difficulty] || 'info'
    }
    
    // 获取前三名的标签类型
    const getTopThreeType = (index) => {
      const types = ['danger', 'warning', 'success']
      return types[index] || 'info'
    }
    
    // 格式化时间
    const formatTime = (seconds) => {
      const min = Math.floor(seconds / 60)
      const sec = seconds % 60
      return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`
    }
    
    // 初始化WebSocket连接
    const initWebSocket = () => {
      // 获取token并检查登录状态
      if (!localStorage.getItem('token')) {
        ElMessage.error('未检测到登录信息，请重新登录')
        router.push('/login')
        return
      }

      // 如果已存在活跃连接，先不关闭
      if (webSocket.value && webSocket.value.readyState === WebSocket.OPEN) {
        console.log('WebSocket连接已存在且处于开启状态，无需重新连接')
        return
      }
      
      // 如果连接正在建立中，也不重复连接
      if (webSocket.value && webSocket.value.readyState === WebSocket.CONNECTING) {
        console.log('WebSocket连接正在建立中，无需重新连接')
        return
      }

      // 关闭旧连接
      if (webSocket.value) {
        try {
          console.log('关闭旧WebSocket连接，当前状态:', getWebSocketStateText(webSocket.value.readyState))
          
          // 移除旧连接的事件监听器，防止事件重复绑定
          webSocket.value.onopen = null
          webSocket.value.onmessage = null
          webSocket.value.onclose = null
          webSocket.value.onerror = null
          
          // 如果不是已关闭状态，则关闭
          if (webSocket.value.readyState !== WebSocket.CLOSED && webSocket.value.readyState !== WebSocket.CLOSING) {
            webSocket.value.close()
          }
        } catch (e) {
          console.error('关闭旧连接失败:', e)
        }
      }
      
      // 使用正确的WebSocket URL
      // 检测环境，在开发环境下使用不同的URL
      let host = window.location.host
      if (process.env.NODE_ENV === 'development') {
        host = 'localhost:8088'
      }
      
      const wsUrl = `ws://${host}/api/ws/contest/${contestId.value}?token=${localStorage.getItem('token')}`
      console.log('正在连接WebSocket:', wsUrl)
      
      try {
        webSocket.value = new WebSocket(wsUrl)
        
        // 标记连接状态
        const connecting = ref(true)
        
        // 连接建立
        webSocket.value.onopen = () => {
          connecting.value = false
          console.log('WebSocket连接已建立，状态:', getWebSocketStateText(webSocket.value.readyState))
          loading.value = false
          ElMessage.success('实时竞赛连接已建立')
          
          // 发送加入竞赛消息
          const joinMessage = {
            type: 'JOIN',
            contestId: contestId.value
          }
          console.log('发送JOIN消息:', joinMessage)
          sendWsMessage(joinMessage)
          
          // 如果5秒内没有收到题目，主动请求当前题目
          setTimeout(() => {
            if (!currentQuestion.value && webSocket.value && webSocket.value.readyState === WebSocket.OPEN) {
              console.log('5秒内未收到题目，主动请求当前题目')
              sendWsMessage({
                type: 'REQUEST_CURRENT_QUESTION',
                contestId: contestId.value
              })
            }
          }, 5000)
        }
        
        // 接收消息
        webSocket.value.onmessage = (event) => {
          try {
            console.log('收到WebSocket消息:', event.data)
            const message = JSON.parse(event.data)
            handleWsMessage(message)
          } catch (error) {
            console.error('解析WebSocket消息失败:', error)
          }
        }
        
        // 连接关闭
        webSocket.value.onclose = (event) => {
          connecting.value = false
          console.log('WebSocket连接已关闭，状态码:', event.code, '原因:', event.reason)
          
          // 避免竞态条件：只有当前连接是被监听的连接时才重连
          // 如果连接不是正常关闭并且竞赛未结束，才尝试重连
          if (!showContestEnd.value && event.code !== 1000) {
            if (!reconnectAttempt.value) {
              ElMessage.warning('与服务器的连接已断开，正在尝试重新连接...')
              
              // 使用指数退避策略进行重连
              const reconnectDelay = Math.min(30000, Math.pow(2, reconnectCount.value) * 1000)
              reconnectAttempt.value = true
              
              console.log(`将在 ${reconnectDelay/1000} 秒后尝试重新连接...`)
              
              setTimeout(() => {
                console.log('尝试重新连接WebSocket...')
                reconnectCount.value++
                reconnectAttempt.value = false
                initWebSocket()
              }, reconnectDelay)
            }
          }
        }
        
        // 连接错误
        webSocket.value.onerror = (error) => {
          connecting.value = false
          console.error('WebSocket连接错误:', error)
          ElMessage.error('与服务器连接发生错误')
        }
      } catch (err) {
        console.error('创建WebSocket连接时发生错误:', err)
        ElMessage.error('创建WebSocket连接失败')
      }
    }
    
    // 声明重连变量
    const reconnectAttempt = ref(false)
    const reconnectCount = ref(0)
    
    // 发送WebSocket消息
    const sendWsMessage = (message) => {
      if (!webSocket.value) {
        console.error('WebSocket未初始化，无法发送消息');
        ElMessage.error('与服务器连接失败，请刷新页面重试');
        return false;
      }
      
      if (webSocket.value.readyState !== WebSocket.OPEN) {
        console.error('WebSocket未连接，当前状态:', getWebSocketStateText(webSocket.value.readyState));
        
        // 根据不同状态给出不同提示
        if (webSocket.value.readyState === WebSocket.CONNECTING) {
          ElMessage.warning('正在连接服务器，请稍后再试...');
        } else {
          ElMessage.error('与服务器连接异常，正在尝试重新连接...');
          
          // 只有在非CONNECTING状态下才尝试重连
          if (webSocket.value.readyState !== WebSocket.CONNECTING && !reconnectAttempt.value) {
            initWebSocket();
          }
        }
        
        return false;
      }
      
      try {
        // 消息序列化
        const messageStr = typeof message === 'string' ? message : JSON.stringify(message);
        console.log('发送WebSocket消息:', messageStr);
        
        // 发送消息
        webSocket.value.send(messageStr);
        return true;
      } catch (error) {
        console.error('发送WebSocket消息失败:', error);
        ElMessage.error('发送消息失败，请稍后重试');
        return false;
      }
    }
    
    // 安全地关闭WebSocket连接
    const safeCloseWebSocket = () => {
      if (webSocket.value) {
        try {
          // 清除所有事件处理器
          webSocket.value.onopen = null;
          webSocket.value.onmessage = null;
          webSocket.value.onclose = null;
          webSocket.value.onerror = null;
          
          // 关闭连接
          if (webSocket.value.readyState === WebSocket.OPEN || 
              webSocket.value.readyState === WebSocket.CONNECTING) {
            console.log('安全关闭WebSocket连接');
            webSocket.value.close(1000, '用户离开页面');
          }
          
          webSocket.value = null;
        } catch (e) {
          console.error('关闭WebSocket连接时发生错误:', e);
        }
      }
    }
    
    // 获取WebSocket状态文本
    const getWebSocketStateText = (state) => {
      switch (state) {
        case WebSocket.CONNECTING: return '正在连接(CONNECTING)';
        case WebSocket.OPEN: return '已连接(OPEN)';
        case WebSocket.CLOSING: return '正在关闭(CLOSING)';
        case WebSocket.CLOSED: return '已关闭(CLOSED)';
        default: return `未知状态(${state})`;
      }
    }
    
    // 处理WebSocket消息
    const handleWsMessage = (message) => {
      try {
        console.log('收到WebSocket消息:', message);
        
        switch (message.type) {
          case 'QUESTION':
            // 收到新题目
            handleNewQuestion(message.data);
            break;
          case 'ANSWER_RESULT':
            // 收到答题结果
            console.log('收到答题结果:', message.data);
            handleAnswerResult(message.data);
            
            // 自动请求下一题（当没有收到自动推送时）
            if (message.data.correct && questionsList.value.length > 0) {
              // 只有当前不是最后一题时才请求下一题
              if (currentQuestionIndex.value < totalQuestions.value - 1) {
                setTimeout(() => {
                  if (!hasReceivedNextQuestion.value) {
                    requestNextQuestion();
                  }
                }, 3000); // 等待3秒，如果没收到下一题，则主动请求
              }
            }
            break;
          case 'RANKING':
            // 收到排名更新
            handleRankingUpdate(message.data);
            break;
          case 'CONTEST_END':
            // 竞赛结束
            handleContestEnd();
            break;
          case 'ERROR': {
            // 处理错误消息
            console.error('服务器返回错误:', message.data);
            ElMessage.error(message.data || '服务器返回错误');
            break;
          }
          default:
            console.warn('未处理的消息类型:', message.type);
        }
      } catch (error) {
        console.error('处理WebSocket消息异常:', error);
      }
    }
    
    // 请求下一题
    const requestNextQuestion = () => {
      if (!webSocket.value || webSocket.value.readyState !== WebSocket.OPEN) {
        ElMessage.warning('WebSocket未连接，无法请求下一题');
        return;
      }
      
      // 如果没有题目列表或已是最后一题，则不请求
      if (questionsList.value.length === 0 || currentQuestionIndex.value >= totalQuestions.value - 1) {
        return;
      }
      
      // 发送请求下一题的消息
      const nextIndex = currentQuestionIndex.value + 1;
      if (nextIndex < questionsList.value.length) {
        const nextQuestionId = questionsList.value[nextIndex].id;
        console.log(`请求切换到下一题: 当前第${currentQuestionIndex.value + 1}题，将切换到第${nextIndex + 1}题`);
        
        sendWsMessage({
          type: 'REQUEST_NEXT_QUESTION',
          contestId: contestId.value,
          questionId: currentQuestion.value?.id,  // 当前题目ID
          nextQuestionId: nextQuestionId          // 下一题ID
        });
      }
    }
    
    // 标记是否已收到下一题
    const hasReceivedNextQuestion = ref(false);
    
    // 处理新题目
    const handleNewQuestion = (questionData) => {
      try {
        // 检查是否是新题目（通过ID比较）
        const isNewQuestion = !lastQuestionId.value || lastQuestionId.value !== questionData.id
        
        if (isNewQuestion) {
          console.log('收到新题目:', questionData)
          
          // 更新上一题ID
          lastQuestionId.value = questionData.id
          
          // 重置已提交答案状态
          hasSubmittedAnswer.value = false
          
          // 标记已收到新题目
          hasReceivedNextQuestion.value = true
          
          // 一段时间后重置标记
          setTimeout(() => {
            hasReceivedNextQuestion.value = false
          }, 5000)
          
          // 启用提交按钮
          const submitBtn = document.querySelector('.submit-btn')
          if (submitBtn) {
            submitBtn.disabled = false
          }
          
          // 通知用户已收到新题目
          ElMessage.success(`已切换到第 ${currentQuestionIndex.value + 1} 题，请在规定时间内作答`)
        }
        
        // 设置当前题目
        currentQuestion.value = questionData
        
        // 根据题目ID在questionsList中查找当前题目的序号
        if (questionsList.value.length > 0) {
          const questionIndex = questionsList.value.findIndex(q => q.id === questionData.id)
          if (questionIndex !== -1) {
            currentQuestionIndex.value = questionIndex
            console.log(`从题目列表中找到当前题目索引: ${questionIndex}, 总题目: ${questionsList.value.length}`)
            // 使用本地题目列表长度更新总题目数
            totalQuestions.value = questionsList.value.length
          } else if (questionData.orderNum) {
            // 如果在列表中找不到但有orderNum，使用orderNum
            currentQuestionIndex.value = questionData.orderNum - 1
            console.log(`使用题目的orderNum: ${questionData.orderNum}`)
          }
        } else {
          // 使用后端返回的题目序号，如果没有则使用orderNum
          if (questionData.currentNumber) {
            currentQuestionIndex.value = questionData.currentNumber - 1
            console.log(`使用后端返回的currentNumber: ${questionData.currentNumber}`)
          } else if (questionData.orderNum) {
            currentQuestionIndex.value = questionData.orderNum - 1
            console.log(`使用题目的orderNum: ${questionData.orderNum}`)
          } else {
            console.warn('无法确定当前题目索引，使用默认值0')
            currentQuestionIndex.value = 0
          }
        }
        
        // 使用后端返回的总题目数，或者本地缓存的题目总数
        if (questionData.totalQuestions && questionData.totalQuestions > 0) {
          totalQuestions.value = questionData.totalQuestions
          console.log(`使用后端返回的总题目数: ${questionData.totalQuestions}`)
        } else if (questionsList.value.length > 0) {
          totalQuestions.value = questionsList.value.length
          console.log(`使用本地题目列表长度: ${questionsList.value.length}`)
        }
        
        // 确保总题目数至少为1，并且不小于当前题号
        if (totalQuestions.value <= 0) {
          totalQuestions.value = Math.max(1, currentQuestionIndex.value + 1);
          console.log(`设置最小总题目数为: ${totalQuestions.value}`);
        } else if (totalQuestions.value < currentQuestionIndex.value + 1) {
          totalQuestions.value = currentQuestionIndex.value + 1;
          console.log(`调整总题目数与当前题号匹配: ${totalQuestions.value}`);
        }
        
        // 重置答案
        userAnswer.value = ''
        userMultipleAnswer.value = []
        
        // 设置答题时间 - 使用服务器指定的时间
        if (questionData.timeLimit > 0) {
          timeLimit.value = questionData.timeLimit
          // 如果服务器提供了剩余时间，使用服务器的时间，否则使用完整时间限制
          remainingTime.value = questionData.remainingTime !== undefined ? 
                               questionData.remainingTime : 
                               questionData.timeLimit
          
          // 当收到新题目时，启动计时器
          if (isNewQuestion) {
            startTimer()
          }
        } else {
          // 默认使用2分钟
          timeLimit.value = 120
          remainingTime.value = 120
          
          if (isNewQuestion) {
            startTimer()
          }
        }
        
        loading.value = false
      } catch (error) {
        console.error('处理新题目时发生错误:', error)
        loading.value = false
        ElMessage.error('加载题目时发生错误，请刷新页面重试')
      }
    }
    
    // 处理答题结果
    const handleAnswerResult = (resultData) => {
      answerCorrect.value = resultData.correct
      
      // 记录已回答的题目
      if (currentQuestion.value && currentQuestion.value.id) {
        if (!answeredQuestions.value.includes(currentQuestion.value.id)) {
          answeredQuestions.value.push(currentQuestion.value.id)
        }
      }
      
      if (resultData.correct) {
        answerResultMessage.value = `获得 ${resultData.score || 0} 分！`
        
        // 如果答对且不是最后一题，则在短暂延迟后自动请求下一题
        if (questionsList.value.length > 0 && currentQuestionIndex.value < totalQuestions.value - 1) {
          setTimeout(() => {
            // 如果3秒内没有收到自动推送的下一题，则主动请求
            if (!hasReceivedNextQuestion.value) {
              requestNextQuestion()
            }
          }, 3000)
        }
      } else {
        answerResultMessage.value = resultData.message || '请继续努力！'
      }
      
      showAnswerResult.value = true
    }
    
    // 处理排名更新
    const handleRankingUpdate = (rankingData) => {
      rankings.value = rankingData
    }
    
    // 处理竞赛结束
    const handleContestEnd = () => {
      // 确保竞赛真的结束，检查是否已完成所有题目
      const allQuestionsAnswered = questionsList.value.length > 0 && 
                                  currentQuestionIndex.value >= questionsList.value.length - 1
      
      console.log('收到竞赛结束消息', {
        当前题目索引: currentQuestionIndex.value,
        总题目数: totalQuestions.value,
        题目列表长度: questionsList.value.length,
        全部题目已回答: allQuestionsAnswered
      })
      
      if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
      }
      
      // 如果确认所有题目都已回答，或者题目列表为空，则显示竞赛结束
      if (allQuestionsAnswered || questionsList.value.length === 0) {
        showContestEnd.value = true
      } else {
        // 否则尝试请求下一题
        ElMessage.warning('系统检测到竞赛可能未完成全部题目，正在尝试继续...')
        setTimeout(() => {
          requestCurrentQuestion()
        }, 3000)
      }
    }
    
    // 开始计时器
    const startTimer = () => {
      if (timer.value) {
        clearInterval(timer.value)
      }
      
      timer.value = setInterval(() => {
        if (remainingTime.value > 0) {
          remainingTime.value--
        } else {
          // 时间到，自动提交
          submitAnswer()
          clearInterval(timer.value)
          timer.value = null
          
          // 时间到了也自动请求下一题（仅管理员）
          const userInfo = localStorage.getItem('userInfo');
          if (userInfo) {
            const userData = JSON.parse(userInfo);
            const isAdmin = userData.roleCode === 'ADMIN' || userData.roleCode === 'TEACHER';
            
            if (isAdmin && currentQuestionIndex.value < totalQuestions.value - 1) {
              setTimeout(() => {
                if (!hasReceivedNextQuestion.value) {
                  requestNextQuestion();
                }
              }, 5000); // 等待5秒后请求下一题
            }
          }
        }
      }, 1000)
    }
    
    // 提交答案
    const submitAnswer = () => {
      if (!currentQuestion.value) {
        ElMessage.warning('当前没有题目可供作答')
        return
      }
      
      // 如果已经提交过答案，不允许再次提交
      if (hasSubmittedAnswer.value) {
        ElMessage.warning('您已提交过答案，无法再次提交')
        return
      }

      let answer = ''
      
      try {
        // 根据题目类型获取答案
        if (currentQuestion.value.typeId === 2) {
          // 多选题，答案用逗号分隔
          if (userMultipleAnswer.value.length === 0) {
            ElMessage.warning('请至少选择一个选项')
            return
          }
          answer = userMultipleAnswer.value.sort().join(',')
        } else if ([1, 3].includes(currentQuestion.value.typeId)) {
          // 单选题或判断题，确保有选择
          if (!userAnswer.value) {
            ElMessage.warning('请选择一个选项')
            return
          }
          answer = userAnswer.value
        } else {
          // 填空题或简答题
          if (!userAnswer.value || userAnswer.value.trim() === '') {
            ElMessage.warning('请输入您的答案')
            return
          }
          answer = userAnswer.value.trim()
        }
        
        // 构建答案消息
        const answerMessage = {
          type: 'SUBMIT_ANSWER',
          contestId: contestId.value,
          questionId: currentQuestion.value.id,
          answer: answer,
          timeUsed: timeLimit.value - remainingTime.value || 0
        }
        
        // 禁用提交按钮，防止重复提交
        const submitBtn = document.querySelector('.submit-btn')
        if (submitBtn) {
          submitBtn.disabled = true
        }
        
        // 记录已提交答案状态
        hasSubmittedAnswer.value = true;
        
        // 记录提交的答案用于调试
        console.log('提交答案数据:', {
          题目ID: currentQuestion.value.id,
          题目类型: currentQuestion.value.typeId,
          题目内容: currentQuestion.value.content?.substring(0, 50) + '...',
          用户答案: answer,
          用时: timeLimit.value - remainingTime.value || 0
        })
        
        // 打印完整消息便于调试
        console.log('发送答题消息JSON:', JSON.stringify(answerMessage))
        
        // 发送WebSocket消息
        const sendResult = sendWsMessage(answerMessage)
        
        if (sendResult) {
          // 显示提交状态
          ElMessage({
            message: '答案已提交，等待结果...',
            type: 'info',
            duration: 2000
          })
          
          // 停止计时器
          if (timer.value) {
            clearInterval(timer.value)
            timer.value = null
          }
        } else {
          // 如果发送失败，启用提交按钮并重置提交状态
          if (submitBtn) submitBtn.disabled = false
          hasSubmittedAnswer.value = false;
        }
      } catch (error) {
        console.error('提交答案时发生错误:', error)
        ElMessage.error('提交答案时发生错误，请重试')
        // 启用提交按钮并重置提交状态
        const submitBtn = document.querySelector('.submit-btn')
        if (submitBtn) submitBtn.disabled = false
        hasSubmittedAnswer.value = false;
      }
    }
    
    // 关闭结果对话框
    const closeResultDialog = () => {
      showAnswerResult.value = false
    }
    
    // 前往排名页面
    const goToRanking = () => {
      router.push(`/contest/ranking/${contestId.value}`)
    }
    
    // 返回竞赛列表
    const goToContestList = () => {
      router.push('/contest/list')
    }
    
    // 获取竞赛信息
    const fetchContestInfo = async () => {
      try {
        const res = await getContestDetail(contestId.value)
        contestInfo.value = res.data
        totalQuestions.value = res.data.questionCount || 0
        loading.value = false
      } catch (error) {
        ElMessage.error('获取竞赛信息失败')
        console.error('获取竞赛信息失败:', error)
      }
    }
    
    // 获取当前用户信息
    const fetchCurrentUser = async () => {
      try {
        const res = await getUserInfo()
        currentUserId.value = res.data.id
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }
    
    // 获取竞赛的所有题目
    const fetchContestQuestions = async () => {
      try {
        const res = await getQuestionsByContestId(contestId.value)
        if (res.code === 200 && res.data) {
          // 按orderNum排序
          questionsList.value = res.data.sort((a, b) => a.orderNum - b.orderNum)
          console.log('已获取竞赛题目列表:', questionsList.value.length, '道题目')
          
          // 更新总题目数
          totalQuestions.value = questionsList.value.length
          
          // 如果已有当前题目，更新当前题目索引
          if (currentQuestion.value) {
            const index = questionsList.value.findIndex(q => q.id === currentQuestion.value.id)
            if (index !== -1) {
              currentQuestionIndex.value = index
              console.log(`更新当前题目索引: ${index}`)
            }
          }
        }
      } catch (error) {
        console.error('获取竞赛题目列表失败:', error)
        // 尝试再次获取
        setTimeout(() => {
          if (questionsList.value.length === 0) {
            console.log('重试获取竞赛题目列表')
            fetchContestQuestions()
          }
        }, 5000) // 5秒后重试
      }
    }
    
    // 添加请求当前题目的方法
    const requestCurrentQuestion = () => {
      if (webSocket.value && webSocket.value.readyState === WebSocket.OPEN) {
        console.log('手动请求当前题目')
        sendWsMessage({
          type: 'REQUEST_CURRENT_QUESTION',
          contestId: contestId.value
        })
      } else {
        ElMessage.warning('WebSocket未连接，正在重新连接...')
        initWebSocket()
      }
    }
    
    // 初始化
    onMounted(() => {
      fetchContestInfo()
      fetchCurrentUser()
      fetchContestQuestions() // 获取题目列表
      initWebSocket()
      
      // 如果5秒后仍然没有题目，主动请求
      setTimeout(() => {
        if (!currentQuestion.value && !loading.value) {
          requestCurrentQuestion()
        }
      }, 5000)
      
      // 添加页面关闭事件，确保WebSocket正确关闭
      window.addEventListener('beforeunload', () => {
        safeCloseWebSocket()
      })
      
      // 定期检查WebSocket连接
      const wsCheckInterval = setInterval(() => {
        if (!webSocket.value || webSocket.value.readyState !== WebSocket.OPEN) {
          console.log('WebSocket连接已断开或未建立，尝试重新连接')
          initWebSocket()
        }
        
        // 如果当前没有题目，尝试请求
        if (!currentQuestion.value && !loading.value) {
          requestCurrentQuestion()
        }
      }, 30000) // 每30秒检查一次
      
      onUnmounted(() => {
        if (wsCheckInterval) {
          clearInterval(wsCheckInterval)
        }
      })
    })
    
    // 在离开页面时清理资源
    onUnmounted(() => {
      if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
      }
      
      // 安全关闭WebSocket
      safeCloseWebSocket()
    })
    
    return {
      contestInfo,
      currentQuestion,
      currentQuestionIndex,
      totalQuestions,
      loading,
      rankings,
      currentUserId,
      userAnswer,
      userMultipleAnswer,
      timeLimit,
      remainingTime,
      showAnswerResult,
      answerCorrect,
      answerResultMessage,
      showContestEnd,
      progressPercentage,
      canSubmitAnswer,
      getQuestionTypeText,
      getDifficultyText,
      getDifficultyType,
      getTopThreeType,
      formatTime,
      submitAnswer,
      closeResultDialog,
      goToRanking,
      goToContestList,
      requestCurrentQuestion,
      questionsList,
      answeredQuestions
    }
  }
}
</script>

<style scoped>
.realtime-contest-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f5f7fa;
}

.loading-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.contest-main {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.contest-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
}

.contest-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.contest-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.contest-timer {
  display: flex;
  align-items: center;
  background-color: #ecf5ff;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.timer-warning {
  animation: pulse 1s infinite;
  color: #f56c6c;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.question-progress {
  background-color: #f0f9eb;
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: bold;
  color: #67c23a;
}

.contest-body {
  display: flex;
  flex: 1;
  gap: 15px;
  height: calc(100% - 70px);
  overflow: hidden;
}

.left-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  min-width: 0;
}

.question-area {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.right-panel {
  width: 300px;
}

.ranking-area {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.ranking-title {
  text-align: center;
  font-size: 18px;
  margin: 0 0 15px 0;
  color: #303133;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.ranking-list {
  flex: 1;
  overflow: hidden;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px 10px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
}

.ranking-item:last-child {
  border-bottom: none;
}

.ranking-item:hover {
  background-color: #f5f7fa;
}

.current-user {
  background-color: #ecf5ff;
}

.rank-position {
  width: 40px;
  text-align: center;
}

.rank-tag {
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  padding: 0;
}

.rank-number {
  font-size: 16px;
  font-weight: bold;
  color: #606266;
}

.rank-user {
  flex: 1;
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.rank-username {
  margin-left: 10px;
  font-size: 14px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.rank-score {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
  margin-left: 10px;
}

.top-three .rank-score {
  color: #e6a23c;
}

.question-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-position {
  background-color: #f5f7fa;
  padding: 8px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
}

.question-number {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.question-total {
  color: #909399;
  font-weight: normal;
  margin-left: 5px;
}

.question-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.question-type,
.question-difficulty {
  font-size: 13px;
}

.question-score {
  font-size: 14px;
  color: #f56c6c;
  font-weight: bold;
}

.question-content {
  margin-bottom: 20px;
}

.question-content h3 {
  font-size: 18px;
  line-height: 1.6;
  margin: 0;
  color: #303133;
}

.question-options {
  margin-bottom: 20px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  width: 100%;
}

.option-group .el-radio,
.option-group .el-checkbox {
  width: 100%;
  margin-right: 0;
  display: flex;
  align-items: center;
}

.option-group .el-radio__input,
.option-group .el-checkbox__input {
  margin-right: 8px;
}

.option-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
}

.option-group .el-radio__label,
.option-group .el-checkbox__label {
  display: flex;
  align-items: center;
  padding-left: 8px;
  width: 100%;
}

.option-item {
  width: 100%;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.option-item:hover {
  background-color: #f0f9ff;
}

.option-key {
  font-weight: bold;
  margin-right: 8px;
  color: #409eff;
  min-width: 30px;
  text-align: left;
}

.option-content {
  color: #303133;
  flex: 1;
  text-align: left;
}

.truth-false {
  display: flex;
  flex-direction: row;
  gap: 20px;
}

.tf-option {
  width: auto;
  min-width: 100px;
  text-align: center;
}

.blank-answer,
.essay-answer {
  width: 100%;
}

.question-actions {
  margin-top: auto;
  display: flex;
  justify-content: center;
  padding-top: 20px;
}

.submit-btn {
  min-width: 120px;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.answer-result,
.contest-end {
  text-align: center;
}

.end-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.no-question {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style> 